package com.henghai.zhenxuan.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;

public class CustomConstraintLayout extends ConstraintLayout {

    public CustomConstraintLayout(Context context) {
        super(context);
    }

    public CustomConstraintLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (getChildCount() < 2) {
            return;
        }
        // 计算左 TextView 和右 TextView 的宽度
        int leftTextViewWidth = getChildAt(0).getMeasuredWidth();
        int rightTextViewWidth = getChildAt(1).getMeasuredWidth();

        // 获取父视图的宽度
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);

        // 计算左 TextView 和右 TextView 的总宽度
        int totalWidth = leftTextViewWidth + rightTextViewWidth;

        // 如果总宽度超过了父视图的宽度，则计算新的高度
        if (totalWidth > parentWidth) {
            // 计算左 TextView 的高度
            int leftTextViewHeight = getChildAt(0).getMeasuredHeight();

            // 计算右 TextView 的高度
            int rightTextViewHeight = getChildAt(1).getMeasuredHeight();


            int leftLines = ((AppCompatTextView) getChildAt(0)).getLineCount();

            // 新的高度等于左 TextView 的高度加上右 TextView 的高度
            int newHeight = leftTextViewHeight / leftLines + rightTextViewHeight;

            // 重新测量高度
            setMeasuredDimension(getMeasuredWidth(), newHeight);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (getChildCount() < 2) {
            return;
        }

        int leftTextViewWidth = getChildAt(0).getMeasuredWidth();
        int rightTextViewWidth = getChildAt(1).getMeasuredWidth();

        // 假设左 TextView 和右 TextView 是两个直接子视图
        AppCompatTextView leftTextView = (AppCompatTextView) getChildAt(0);
        View rightTextView = getChildAt(1);

        int parentWidth = getWidth();
        int totalWidth = leftTextViewWidth + rightTextViewWidth;

        if (totalWidth > parentWidth) {
            // 如果总宽度超过了父视图的宽度，则将右 TextView 下移到第二行的位置
            int leftTextViewHeight = leftTextView.getMeasuredHeight();
            int leftLines = leftTextView.getLineCount();
            rightTextView.layout(parentWidth - rightTextViewWidth, leftTextViewHeight / leftLines, parentWidth, leftTextViewHeight / leftLines + rightTextView.getMeasuredHeight());
        }
    }
}